package com.incom.log.server.monitor.telnet;

import com.incom.log.server.conf.ServiceConfig;
import com.incom.log.server.monitor.ServiceMonitor;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

public class TelnetServer extends ServiceMonitor {

    private ServerSocket serverSocket;

    private void connect(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setReuseAddress(true);
    }

    @Override
    public void stopMonitor() throws Exception {
        ServiceConfig.serverRunSts = false;
    }

    @Override
    public void initMonitor(Properties properties) throws Exception {
        String property = properties.getProperty("log-monitor.port");
        if(property != null) {
            this.connect(Integer.parseInt(property));
            return;
        }
        this.connect(9999);
    }

    @Override
    public void startMonitor() throws Exception {
        new Thread(this).start();
    }

    public static void main(String[] args) {
        try {
            TelnetServer server = new TelnetServer();
            server.connect(9999);
            server.startMonitor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(ServiceConfig.serverRunSts) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }
            new HandlerThread(socket).start();
        }
    }
}
